package com.wei.lawyer.net.presenter;

import android.text.TextUtils;

import com.trello.rxlifecycle2.LifecycleProvider;
import com.wei.lawyer.model.BaseDataBean;
import com.wei.lawyer.model.BaseResultBean;
import com.wei.lawyer.model.ConfigBean;
import com.wei.lawyer.model.TokenBean;
import com.wei.lawyer.model.UserBean;
import com.wei.lawyer.net.ApiService;
import com.wei.lawyer.net.BaseObserver;
import com.wei.lawyer.net.BasePresenter;
import com.wei.lawyer.net.BaseView;
import com.wei.lawyer.net.RetrofitManager;
import com.wei.lawyer.utils.RxUtils;

import java.io.File;

import javax.annotation.Nullable;

import io.reactivex.Flowable;
import io.reactivex.functions.BiFunction;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 作者：赵若位
 * 时间：2018/11/29 18:05
 * 邮箱：1070138445@qq.com
 * 功能：
 */
public class UserPresenter extends BasePresenter<BaseView>
{
    public UserPresenter(BaseView view, LifecycleProvider provider)
    {
        super(view, provider);
    }


    /**
     * 获取App配置说明和收费价格
     */
    public void getConfig()
    {
        add(
                RetrofitManager.getManager().getService()
                        .getConfig()
                        .compose(this.<BaseDataBean<ConfigBean>>loadTransformer())
                        .compose(RxUtils.<ConfigBean>handleBaseData())
                        .subscribeWith(new BaseObserver<ConfigBean>(mView)
                        {
                            @Override
                            public void onNext(ConfigBean config)
                            {
                                if (mView != null)
                                {
                                    mView.showData(config);
                                }
                            }
                        })
        );
    }

    /**
     * 用户账号，密码进行登录
     *
     * @param account
     * @param passWord
     */
    public void login(String account, String passWord)
    {
        add(
                RetrofitManager.getManager().getService()
                        .login(account, passWord)
                        .compose(this.<BaseDataBean<TokenBean>>loadTransformer())
                        .compose(RxUtils.<TokenBean>handleBaseData())
                        .subscribeWith(new BaseObserver<TokenBean>(mView)
                        {
                            @Override
                            public void onNext(TokenBean token)
                            {
                                if (mView != null)
                                {
                                    mView.showData(token);
                                }
                            }
                        })
        );
    }

    /**
     * 获取手机验证码
     *
     * @param account
     * @param reset
     */
    public void getPhoneCode(String account, boolean reset)
    {
        add(
                RetrofitManager.getManager().getService()
                        .getPhoneCode(account, reset)
                        .compose(this.<BaseDataBean<Object>>loadTransformer())
                        .compose(RxUtils.<Object>handleBaseData())
                        .subscribeWith(new BaseObserver<Object>(mView)
                        {
                            @Override
                            public void onNext(Object o)
                            {
                                if (mView != null)
                                {
                                    mView.showData(o);
                                }
                            }
                        })
        );
    }

    /**
     * 重置用户密码，并自动登陆
     *
     * @param account
     * @param password
     * @param code
     */
    public void forgetPassword(final String account, final String password, String code)
    {
        //TODO 需要修改忘记密码自动登陆逻辑
        add(
                RetrofitManager.getManager().getService()
                        .forgetPassWord(account, password, code)
                        .compose(this.<BaseDataBean<Object>>loadTransformer())
                        .compose(RxUtils.handleBaseData())
                        .subscribeWith(new BaseObserver<Object>(mView)
                        {
                            @Override
                            public void onNext(Object o)
                            {
                                login(account, password);
                            }
                        })
        );
    }

    /**
     * 注册新用户
     *
     * @param account
     * @param password
     * @param code
     */
    public void register(final String account, final String password, String code)
    {
        //TODO 需要修改注册成功自动登录
        add(
                RetrofitManager.getManager().getService()
                        .register(account, password, null, code)
                        .compose(this.<BaseDataBean<TokenBean>>loadTransformer())
                        .compose(RxUtils.<TokenBean>handleBaseData())
                        .subscribeWith(new BaseObserver<TokenBean>(mView)
                        {
                            @Override
                            public void onNext(TokenBean token)
                            {
                                mView.showData(token);
                            }
                        })
        );
    }

    /**
     * 获取用户信息和账户余额
     */
    public void getUserInfo()
    {
        ApiService api = RetrofitManager.getManager().getService();

        Flowable<UserBean> info = api.getUserInfo()
                .compose(RxUtils.<UserBean>handleBaseData());
        Flowable<UserBean> asset = api.getUserAsset()
                .compose(RxUtils.<UserBean>handleBaseData());

        add(Flowable.zip(info, asset, new BiFunction<UserBean, UserBean, UserBean>()
        {
            @Override
            public UserBean apply(UserBean info, UserBean asset) throws Exception
            {
                info.setPoint(asset.getPoint());
                info.setCash(asset.getCash());
                return info;
            }
        }).compose(this.<UserBean>loadTransformer())
                .subscribeWith(new BaseObserver<UserBean>(mView)
                {
                    @Override
                    public void onNext(UserBean data)
                    {
                        if (mView != null)
                        {
                            mView.showData(data);
                        }
                    }
                }));
    }


    /**
     * 修改用户头像
     *
     * @param file
     */
    public void setAvatar(File file)
    {
        if (file == null || (!file.exists())) return;
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("avatar", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .addFormDataPart("imgFileSize", String.valueOf(file.length()))
                .build();
        add(
                RetrofitManager.getManager().getService().setAvatar(body)
                        .compose(this.<BaseResultBean<String>>loadTransformer())
                        .compose(RxUtils.<String>handleBaseResult())
                        .subscribeWith(new BaseObserver<String>(mView)
                        {
                            @Override
                            public void onNext(String s)
                            {
                                if (mView != null)
                                {
                                    mView.showData(s);
                                }
                            }
                        })
        );
    }


    /**
     * 修改用户基本资料
     *
     * @param user
     */
    public void modifyUserData(@Nullable final UserBean user)
    {
        RequestBody body = new FormBody.Builder()
                .add("nickName", TextUtils.isEmpty(user.getNickName()) ? "" : user.getNickName())
                .add("location", TextUtils.isEmpty(user.getLocation()) ? "" : user.getLocation())
                .add("gender", String.valueOf(user.isGender()))
                .add("description", TextUtils.isEmpty(user.getDescription()) ? "" : user.getDescription())
                .build();
        add(
                RetrofitManager.getManager().getService().modifyUserData(body)
                        .compose(this.<BaseDataBean<Object>>loadTransformer())
                        .compose(RxUtils.handleBaseData())
                        .subscribeWith(new BaseObserver<Object>(mView)
                        {
                            @Override
                            public void onNext(Object o)
                            {
                                if (mView != null)
                                {
                                    mView.showData(user);
                                }
                            }
                        })
        );
    }


}
